package com.ldk.admin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.CONFIG;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.constants.SESSION;
import com.ldk.framework.entity.*;
import com.ldk.framework.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.constants.ViewMode;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.enums.PlatformUserType;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * A.4.6、网约车平台公司运价信息
 *
 * @author xiangwl
 * 2018年8月9日
 * com.ldk.admin.controller
 * CompanyfareController
 */
@Controller
@RequestMapping("/baseinfo")
public class CompanyfareController extends BaseController {
    /**
     * 路由地址
     */
    private final String route = "baseinfo";
    /**
     * 模块名称
     */
    private final String module = "公司运价信息";
    @Autowired
    private ICompanyfareService companyfareService;
    @Autowired
    private ICompanypermitService companypermitService;
    @Autowired
    private IAreaService areaService;

    @RequestMapping("/companyfare/list")
    public ModelAndView edit(ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);

        setLinks(map, "", "", module + "管理", "/" + route + "/companyfare/list", "添加" + module, "/" + route + "/companyfare/add");
        map.addAttribute("route", route);
        map.addAttribute("module", module);
        map.addAttribute("areaList", getAreaList());
        map.addAttribute("companyList", getCompanyList());

        return new ModelAndView("/baseinfo/companyfare/list");
    }

    @ResponseBody
    @RequestMapping("/companyfare/getList")
    public LigerUIGridResult<Companyfare> getList(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                                  @RequestParam(value = "pagesize", required = false, defaultValue = "10") int pageSize,
                                                  @RequestParam(value = "searchKey", required = false, defaultValue = "") String searchKey,
                                                  HttpServletRequest request) {
        int limit = pageSize;
        int offset = (page - 1) * pageSize;

        Companyfare query = new Companyfare();
        if (!StringUtils.isBlank(searchKey)) {
            query.setSearchKey(searchKey);
        }
        AdminUser admin = (AdminUser) request.getSession().getAttribute(SESSION.USER);
        if (admin != null && admin.getRoleId() == CONFIG.COMPANY_ROLEID) {
            query.setCompanyId(admin.getCompanyId());
        }

        CustomPageable pageable = new CustomPageable(offset, limit);

        Page<Companyfare> result = companyfareService.selectPageList("", query, pageable);

        LigerUIGridResult<Companyfare> grid = new LigerUIGridResult<>();
        grid.Total = result.getTotalElements();
        grid.Rows = result.getContent();

        return grid;
    }

    @RequestMapping("/companyfare/add")
    public ModelAndView add(ModelMap map, HttpServletRequest request,
                            HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        if (getRoleId(request) == 4) {
            setLinks(map, module + "管理", "/" + route + "/companyfare/list", "", "", "", "");
        } else {
            setLinks(map, module + "管理", "/" + route + "/companyfare/list", "添加" + module, "/" + route + "/companyfare/add", "", "");
        }
        setForm(map, "/" + route + "/companyfare/insert", null);
        map.addAttribute("module", module);
        map.addAttribute("areaList", getAreaList());
        map.addAttribute("companyList", getCompanyList());

        Companyfare model = new Companyfare();

        return new ModelAndView("/baseinfo/companyfare/info", "model", model);
    }

    @RequestMapping("/companyfare/edit/{id}")
    public ModelAndView edit(@PathVariable long id, ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        Companyfare query = new Companyfare();
        query.setId(id);

        Companyfare model = companyfareService.selectOne("", query);
        if (model == null) {
            return new ModelAndView("redirect:/" + route + "/companyfare/list");
        }
        setLinks(map, module + "管理", "/" + route + "/companyfare/list", "编辑" + module, "/" + route + "/companyfare/edit/" + id, "", "");
        setForm(map, "/" + route + "/companyfare/update", null);
        map.addAttribute("module", module);
        map.addAttribute("areaList", getAreaList());
        map.addAttribute("companyList", getCompanyList());

        return new ModelAndView("/baseinfo/companyfare/info", "model", model);
    }

    @RequestMapping("/companyfare/insert")
    public ModelAndView insert(@ModelAttribute("model") Companyfare model,
                               RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
        try {
            model.setCreateTime(SystemUtil.getAllSeconds());
            if (model.getEnabled() == null) {
                model.setEnabled(true);
            }
            int row = companyfareService.insert("", model);

            if (row > 0) {
                rst.AddOk("添加" + module + "成功");
            } else {
                rst.AddError("添加" + module + "失败");
            }
        } catch (Exception e) {
            rst.AddError("添加" + module + "失败");
            logger.error(e.getMessage());
        }
        return new ModelAndView("redirect:/" + route + "/companyfare/add");
    }

    @RequestMapping("/companyfare/update")
    public ModelAndView update(@ModelAttribute("model") Companyfare model,
                               RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();

        redAttr.addAttribute("id", model.getId());
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

        try {
            int row = companyfareService.updateByKey("", model);
            if (row > 0) {
                rst.AddOk("修改" + module + "成功");
            } else {
                rst.AddError("修改" + module + "失败");
            }
        } catch (Exception e) {
            rst.AddError("修改" + module + "失败");
            logger.error(e.getMessage());
        }

        return new ModelAndView("redirect:/" + route + "/companyfare/edit/{id}");
    }

    /**
     * 浏览
     *
     * @param id
     * @param map
     * @return
     */
    @RequestMapping("/companyfare/view/{id}")
    public ModelAndView view(@PathVariable long id, ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);

        setViewMode(map, ViewMode.View);
        Companyfare query = new Companyfare();
        query.setId(id);
        Companyfare model = companyfareService.selectOne("", query);

        map.addAttribute("module", module);

        return new ModelAndView("/baseinfo/companyfare/info", "model", model);
    }

    @ResponseBody
    @RequestMapping("/companyfare/remove/{id}")
    public ResponseResult remove(@PathVariable long id, HttpServletRequest request) {

        ResponseResult rst = new ResponseResult();
        if (id < 1) {
            rst.AddError("删除" + module + "错误");
            return rst;
        }
        Boolean successed = false;
        try {
            Companyfare query = new Companyfare();
            query.setId(id);
            int row = companyfareService.deleteByKey("", query);
            successed = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (successed) {
            rst.AddOk("删除" + module + "成功");
        } else {
            rst.AddError("删除" + module + "失败");
        }

        return rst;
    }

    /**
     * 获取开通城市列表
     *
     * @return
     */
    private List<Area> getAreaList() {
        Area query = new Area();
        query.setEnabled(true);

        List<Area> regions = areaService.selectList("", query);
        return regions;
    }

    /**
     * 获取分公司列表
     *
     * @return
     */
    private List<Companypermit> getCompanyList() {
        Companypermit query = new Companypermit();
        query.setEnabled(true);

        return companypermitService.selectList("", query);
    }
}
